/**
 * 快进快出分析器 - 对象中心化版本
 * 检测资金在短时间内流入后迅速流出的异常行为
 */

class FastPassAnalyzer extends BaseAnalyzer {
  constructor(caseId, targetSubject = null) {
    super(caseId, targetSubject);
    this.name = '快进快出';
    this.description = '检测资金短时间内流入后迅速流出的异常模式';
  }

  /**
   * 执行快进快出分析
   * @param {Object} params { timeWindowHours: 数小时内, minAmount: 最小金额 }
   */
  async analyze(params = {}) {
    const timeWindowHours = params.timeWindowHours || 2;
    const minAmount = params.minAmount || 50000;

    // 构建账号过滤条件
    const accountFilter = this.getBankAccountFilter();
    const targetInfo = this.targetSubject
      ? `针对 "${this.targetSubject.name}" 的 ${this.targetSubject.accounts.bank.length} 个账户`
      : '全量数据';

    console.log(`[FastPassAnalyzer] 开始分析 (${targetInfo})`);

    const sql = `
            WITH InTransactions AS (
                SELECT 
                    account_card,
                    customer_name,
                    transaction_time,
                    transaction_amount as in_amount,
                    counterparty_name as in_from
                FROM bank_transactions
                WHERE case_id = ?
                    AND debit_credit_flag = '借'
                    AND transaction_amount >= ?
                    ${accountFilter}
            ),
            OutTransactions AS (
                SELECT 
                    account_card,
                    transaction_time,
                    transaction_amount as out_amount,
                    counterparty_name as out_to
                FROM bank_transactions
                WHERE case_id = ?
                    AND debit_credit_flag = '贷'
                    ${accountFilter}
            )
            SELECT 
                i.account_card,
                i.customer_name,
                i.transaction_time as in_time,
                i.in_amount,
                i.in_from,
                o.transaction_time as out_time,
                o.out_amount,
                o.out_to,
                CAST((julianday(o.transaction_time) - julianday(i.transaction_time)) * 24 AS REAL) as hours_diff
            FROM InTransactions i
            JOIN OutTransactions o ON i.account_card = o.account_card
            WHERE o.transaction_time > i.transaction_time
                AND (julianday(o.transaction_time) - julianday(i.transaction_time)) * 24 <= ?
                AND ABS(o.out_amount) >= i.in_amount * 0.8
            ORDER BY hours_diff ASC, i.in_amount DESC
            LIMIT 100
        `;

    const result = await this.runQuery(sql, [
      this.caseId, minAmount,
      this.caseId,
      timeWindowHours
    ]);

    if (!result.success) {
      return this.createResult('fast_pass', this.name, [], '查询失败: ' + result.message, 'danger');
    }

    const data = result.data;
    const summary = data.length > 0
      ? `检测到 ${data.length} 笔快进快出交易，最快 ${data[0].hours_diff.toFixed(1)} 小时完成进出`
      : `未检测到 ${timeWindowHours} 小时内的快进快出交易`;

    const level = data.length > 10 ? 'danger' : (data.length > 0 ? 'warning' : 'info');

    return this.createResult('fast_pass', this.name, data, summary, level);
  }

  renderResult(data) {
    if (!data || data.length === 0) {
      return '<div class="empty-result" style="padding:40px; text-align:center; color:#999;">✓ 未发现快进快出异常</div>';
    }

    let html = `
      <div class="result-summary" style="padding:15px; background:#fef0f0; border-left:4px solid #f56c6c; margin-bottom:15px;">
        <strong>⚡ 发现 ${data.length} 笔快进快出交易</strong>
        <p style="margin:5px 0 0; font-size:0.9rem;">资金短时间内流入后迅速流出，可能存在洗钱或过账行为</p>
      </div>
      
      <table class="analysis-result-table" style="width:100%; border-collapse:collapse; font-size:0.9rem;">
        <thead style="background:#f5f7fa;">
          <tr>
            <th style="padding:10px; border:1px solid #e0e0e0;">账号/户名</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">流入时间</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:right;">流入金额</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">流出时间</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:right;">流出金额</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:center; background:#fff3cd;">时间差(小时)</th>
          </tr>
        </thead>
        <tbody>
    `;

    data.forEach((row, index) => {
      const rowStyle = index % 2 === 0 ? 'background:#fafafa;' : '';
      html += `<tr style="${rowStyle}">`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.customer_name}<br><small style="color:#909399; font-family:monospace;">${row.account_card}</small></td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${this.formatDate(row.in_time)}</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:right; color:#67c23a; font-weight:bold;">¥${this.formatAmount(row.in_amount)}</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0;">${this.formatDate(row.out_time)}</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:right; color:#f56c6c; font-weight:bold;">¥${this.formatAmount(row.out_amount)}</td>`;
      html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:center; font-weight:bold; color:#e6a23c;">${row.hours_diff.toFixed(1)}</td>`;
      html += '</tr>';
    });

    html += '</tbody></table>';
    return html;
  }
}

window.FastPassAnalyzer = FastPassAnalyzer;
